package com.coder4j.starter.web.util;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;

import java.util.Objects;

/**
 * 应用上下文获取
 * @author keller
 * @date 2025-11-21 09:41:13
 */
@Component
@Slf4j
public class ApplicationContextProvider implements ApplicationContextAware {

    private static ApplicationContext applicationContext;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        ApplicationContextProvider.applicationContext = applicationContext;
    }

    /**
     * 获取应用上下文
     * @return
     */
    public static ApplicationContext getApplicationContext() {
        return ApplicationContextProvider.applicationContext;
    }

    public static  <T> T getBean(Class<T> clazz){
        return applicationContext.getBean(clazz);
    }

    public static Object getBean(String beanName){
        return applicationContext.getBean(beanName);
    }

    /**
     * 获取环境变量值
     * @param key 键
     * @param defaultValue 默认值
     * @return 值
     */
    public static String getEnvironmentVariableWithDefault(String key, String defaultValue) {
        if(applicationContext == null){
            log.error("getEnvironmentVariable  applicationContext is null");
            return defaultValue;
        }
        Environment environment = applicationContext.getEnvironment();
        String value = environment.getProperty(key);
        return Objects.isNull(value) ? defaultValue : value;
    }

    public static String getEnvironmentVariable(String ... keys) {
        if(applicationContext == null){
            log.error("getEnvironmentVariable  applicationContext is null");
            return null;
        }

        Environment environment = applicationContext.getEnvironment();
        if(keys.length == 1){
            return environment.getProperty(keys[0]);
        }
        StringBuilder value = new StringBuilder();
        for (String key : keys) {
            value.append(environment.getProperty(key));
        }
        return value.toString();
    }
}
